/**
 * 登录模块，提供登录相关业务功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "datagridServ","msgServ", "ajaxServ", "formServ","sysmanMain", "bizProto","btnServ","buttonEvent","flowInit"],
		function($,datagridServ, msgServ, ajaxServ, formServ,sysmanMain, bizProto,btnServ,buttonEvent,flowInit) {

			'use strict';

			var _bizProto,_buttonConfig,_moduleConfig,
			    //搜索框和高级查找div
				$searchbox,
				//锚记datagrid目标元素
				$dg,
				//初始化后的datagrid dom对象
				$grid,
				//编辑弹窗对象及弹窗按钮对象
				$edit_window,window_btn,
				//设置密码弹窗对象及按钮对象
				$password_window,password_btn,
				//业务表单对象
				$form,
				//部门选择框字段
				$deptNameField, $deptIdField,formEl, formData = 0, 
				editPageUrl,passwordPageUrl,passwordSaveUrl,
				
				//根节点id
				rootid= 'panel-oa-addressList',
				//编辑窗口id
				window_id = 'oa-addressList-win',
				
				//当前选中部门
				curDept,
				
				querylistUrl,
				
				userInitializd = false,
				
				baseDeptQueryUrl = "/department/getTree.action",deptQueryUrl,
				
				deptTreeUrl = "/department/query/getTreeList.action"

			var public_method = {				
				
				initList:function(doc){
					userInitializd = false;
					private_method.init(doc);
				},
				initEdit:function(_options){
					private_method.initEdit();					
				},
				
				/**
				 * 新增、编辑响应事件
				 */
				editEvent:function(_options){
					
					var rootPath = '/'+sysmanMain.getRootPath();
					var _url ='/oaAddressList/query/editPage.action';
					var _param = {
						href:rootPath+_url,
						onClose:function(){
							$('#'+window_id).empty();
						}
					}				
					
					$.extend(_param,_options)
					datagridServ.windowEdit(_param);
				},
				buttonExtends:function(){
					var ret = {
						'编辑':private_method.editEvent,
						"导出当前页":function(){private_method.exportExcel()},
						"导出全部":function(){private_method.exportExcel({type:'all'})}};
					return  ret
				}
			}

			var private_method = {
				
				initEdit:function(){
					//初始化部门选择框
					if(window.console){
						console.log(' oaAddressList loaded...');
					}
					$deptNameField = $('#'+window_id + ' #deptName')
					$deptIdField = $('#'+window_id + ' #deptid')
					$($deptIdField).combotree({
						width:171,
						url:deptQueryUrl,
						idFiled:'id',
					 	textFiled:'name',
					 	parentField:'parentid',
					 	onClick:function(node){private_method.setComboValue(node,$deptNameField)}					 	
					});
					
					
					$edit_window = $('#oa-addressList-win')
					$password_window = $('#userpassword-win');
					//初始化操作按钮
					
				},
				init : function(_options) {
					if (window.console) {
					console.info('user modules gets ready and been loaded.');
					}
					//_moduleConfig = sysmanMain.getCurrentModuConfig();
					//_bizProto = new bizProto({doc:doc,rootid:'panel-oa-addressList',panelSelector:'div.well',subSystemCode:'oa',moduleCode:'oaAddressList'})
					
					_defaultConfig = $.extend({},_defaultConfig,_options)			
					_bizProto = new bizProto(_defaultConfig);			
					_bizProto.gridHeight -= 15
					
					_buttonConfig={
						"新增":private_method.add,
					    "编辑":private_method.modify,
						 "删除":private_method.del,
						 "设置密码":private_method.setPassword							
					}
					private_method.initPath();
					private_method.initDept();
					private_method.initUser();
					$.messager.progress('close');
				},
				
				//初始化路径
				initPath:function(){					
					passwordSaveUrl = _bizProto.rootPath +'/user/securityUserPasswordReset.action';
					deptQueryUrl = _bizProto.rootPath +baseDeptQueryUrl;
					editPageUrl = _bizProto.rootPath +'/user/query/editPage.action';
					passwordPageUrl = _bizProto.rootPath +'/user/userPasswordPage.action';
				},
				
				
				//初始化元素
				initUser:function(doc){
					
					
					$dg = $('#' + rootid + ' div.dg-user');
					var _userParam={
						height:_bizProto.pageHeight,						
						width : 'auto',
						pagination : true,
						rownumbers : true,
						fitColumns : true,
						border : true,
						singleSelect : true,
						striped : true,
						url : _bizProto.queryListUrl,
						columns : [[
							{field : 'ck',checkbox : true}, 
							{field : 'id',title : '用户编码',width :20,align : 'left',editor : "text"}, 
							{field : 'loginName',title : '用户账号',width :40,align : 'left',editor : "text"}, 
							{field : 'name',title : '用户名',width :40,editor : 
								{type : 'validatebox',options : 
									{required : true}
								}
							},
							{field : 'email',title : '电子邮箱',width :40,align : 'left',editor : 
								{type : 'validatebox',options : 
									{required : true,validType : 'email'}
								}
							},
							{field : 'workphone',title : '办公电话',width : 30,editor : "validatebox"}, 							 
							{field : 'mobile',title : '联系电话',width : 30,align : 'left',editor : "text"}, 
							
							{field : 'deptName',title : '所属部门',width : 40,align : 'left',editor : "text"}, 
							{field : 'comments',title : '描述',width : 20,align : 'left',editor : "text"}
						]],
						toolbar : '#'+rootid +' div.tb-user'
					};				
					
					if(curDept && curDept.id){
						
						_userParam.queryParams={condition:{deptid:curDept.id}}
					}
					$grid = $dg.datagrid(_userParam)
					userInitializd = true;
					
					// 搜索框
					$("#searchbox").searchbox({
						menu : '#'+rootid+' div.search-mm',
						prompt : '模糊查询',
						searcher : function(value, name) {
							var obj = {};
							obj["searchName"]=name;
							obj["searchValue"]=value;							
							$dg.datagrid('reload', obj);
						}

					});
					var listTd = $('#'+rootid +' div.tb-user td.list-btn')
									
					
					var _param = {
						bizcode:_moduleConfig.fullBizcode,
						rootPath:_bizProto.rootPath,
						container:listTd,
						callback:private_method.bindBtnEvent}
					btnServ.generateListBtn(_param);

				},
				
				initDept:function(){
					var $dept = $('#'+rootid + ' div.tg-department');
			
			
					//部门信息
					if($dept && $dept.length>0){
						var _deptParam = {
							rownumbers:true,
							animate: true,
							idField: 'id',
							treeField: 'name',
							striped:true,
							border:true,
							fitColumns: true,
							height : _bizProto.gridHeight,
							url : _bizProto.rootPath + deptTreeUrl,
							onClickRow:private_method.getUsers,
							columns:[[						
								{field:'name',title:'部门名称',width:60,halign:'center'}									
							]]
						}
						$dept.treegrid(_deptParam)
						
					}
				},
				
				getUsers:function(data){
					curDept = data;
					var $user = $('#'+rootid +" div.dg-user");
					if($user &&　$user.length>0){
						
						if(userInitializd){
							$user.datagrid('load',{condition:{deptid:data.id}})
						}else{
//							$user.datagrid({
//								height : _bizProto.gridHeight,
//								url : _bizProto.rootPath + findUserUrl,								
//								queryParams:{deptid:data.id}
//							});
							private_method.initUser();
						}
					
					}
				},
				
				//绑定按钮事件
				bindBtnEvent:function(){
					// 绑定按钮事件
					var btn = $('#' + rootid + ' a.function-btn')
					$(btn).unbind('click');
					$(btn).bind('click', private_method.function_btn_listenner)						
				},
				
				setComboValue:function(node,target){
		    		if(node!=null){		    			
		    			$(target).val(node.text);
		    		}
		    	},
				//功能按钮监听函数
				function_btn_listenner:function(e){
					
					btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})
					
				},
				// 新增函数
				add : function() {
					$($grid).datagrid('clearSelections')
					private_method.edit(false);

				},
				modify:function(){
					private_method.edit(true);
				},
				// 编辑,flag 为form按钮可见性标志
				edit : function(flag) {
					$edit_window = $('#' + window_id)
					var _param = {grid:$grid,window:$edit_window,href:editPageUrl,width:600,height:400,flag:flag}
					datagridServ.windowEdit(_param);
				},
				
				// 设置密码,flag 为form按钮可见性标志
				setPassword : function(flag) {
					$password_window = $('#userpassword-win');
					var _param = {grid:$grid,window:$password_window,href:passwordPageUrl,width:400,height:300}
					datagridServ.windowEdit(_param);
				},
				
				// 删除
				del : function() {
					
					datagridServ.delRow({url:userDelUrl,target:$grid});
				},
				// 提交form
				submit : function() {
					
					datagridServ.save({form:$form,grid:$grid,url:userSaveUrl})					
				},
				
				
				//
				cancel : function() {
					$($edit_window).window('close');
				},
				updCellTree:function (record){
				/*var rows = $dg.datagrid('getSelections');
				$.each(rows,function(i,row){
					if (row) {
						var rowIndex = $dg.datagrid('getRowIndex', row);
						$dg.datagrid('getEditor',{'index':rowIndex,'field':'organizeName'}).target.val(record.text);
					}
				});*/
					var rowIdx = $grid.datagrid('getRowIndex',$grid.datagrid('getSelected'));
					 $grid.datagrid('getEditor',{'index':rowIdx,'field':'organizeName'}).target.val(record.text);
	
				},
				/**
				 * 导出excel
				 */
				exportExcel:function(_options){
					var _param = private_method.getConditionAll()
					//var _url 
					_moduleConfig =sysmanMain.getCurrentModuConfig();
					
					//var rootPath = '/'+sysmanMain.getRootPath();

					if(_moduleConfig.querylistUrl){
						
						var _moduPath
						if(_moduleConfig.queryModule){
							_moduPath =_moduleConfig.queryModule 
						}else{
							_moduPath =_moduleConfig.moduleCode 
						}
						var _url = '/'+ sysmanMain.getRootPath() + '/oaAddressList/query/exportExcel.action';
						//_url = _bizProto.rootPath  +'/'+_moduPath +'/query/' +'exportExcel.action'
					}else{
						_url = bizProto.queryListUrl
					}
					if(_options && _options.type &&_options.type==='all'){
							buttonEvent.exportAll({url:_url,queryParam:_param})
							return
					}else{
						buttonEvent.exportCurrent({url:_url,queryParam:_param})
					}
					
				},
				/**
				 * 获取查询参数
				 */
				getConditionAll:function(){
					var _param={}
					//获取当前模块配置
					_moduleConfig =sysmanMain.getCurrentModuConfig();			
					
					if(rootid)
						$dg= $('#' + rootid + " table.dg-detail");	
					
					if($dg.length>0){
						var _tmpSearch = private_method.getSearchValue()
						var _tmpCondition = private_method.getConditionValue()
						
						_param = $.extend({},_tmpSearch,_tmpCondition)				
					}					
					return _param
				},
				/*
				 * 获取模糊查找框内容
				 */
				getSearchValue:function(){
					var _config = private_method.getCurrentConfig();
					var ret={};
					if(_config && _config.rootid){
						
						$searchbox = $("#"+_config.rootid +" input.searchbox")
						if($searchbox.length>0){
							var _searchName, _searchValue
							//取值
							_searchValue = $($searchbox).searchbox()
							if(_searchValue){
								_searchValue = $.trim(_searchValue)
								if(_searchValue==='')
									return
							}			
								
							//取名称
							var _searchName = $($searchbox).searchbox('getName')
							if(_searchName){
								_searchName =$.trim(_searchName)
								if(_searchName===''){
									return
								}															
							}
							
							ret[_searchName]=_searchValue;
							
							return ret
						}
						
					}
				},
				/*
				 * 获取当前模块配置信息
				 */
				getCurrentConfig:function(){
					var _config =sysmanMain.getCurrentModuConfig();
					if(!_config){
						msgServ.Msgslide('获取模块配置信息出错')			
					}			
					return _config
				},
				//获取高级查询内容
				getConditionValue:function(){
					
					var ret={}
					//获取当前模块配置
					_moduleConfig =private_method.getCurrentConfig();
					if(_moduleConfig){
							
						
						
						var _conditonParam ={}
						var _conditonFunc =_moduleConfig.conditionExtends
						//rootid是否存在
						if(_moduleConfig.rootid && 
							_moduleConfig.conditionForm){
							
							var _form = $('#'+_moduleConfig.rootid +' ' + _moduleConfig.conditionForm)
							ret = formServ.getDataObj({
								rootid:_moduleConfig.rootid,
								form : $(_form)
							});											
						}				
					}
					return ret
					 
				}
			};
			return public_method;
		});